<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var socket;
        //判断当前浏览器是否支持websocket
        if (window.WebSocket) {
            //go on
            socket = new WebSocket("ws://localhost:7000/chat");
            //相当于channelReado, ev 收到服务器端回送的消息
            socket.onmessage = function (ev) {
                var rt = document.getElementById("responseText");
                rt.value = rt.value + "\n" + ev.data;
            }

            //相当于连接开启(感知到连接开启)
            socket.onopen = function (ev) {
                var rt = document.getElementById("responseText");
                rt.value = "连接开启了.."
                var userId = document.getElementById("userId").value;
                var myObj = {userId: userId};
                var myJSON = JSON.stringify(myObj);
                socket.send(myJSON)
            }

            //相当于连接关闭(感知到连接关闭)
            socket.onclose = function (ev) {
                var rt = document.getElementById("responseText");
                rt.value = rt.value + "\n" + "连接关闭了.."
            }
        } else {
            alert("当前浏览器不支持websocket")
        }

        //发送消息到服务器
        function send(message) {
            if (!window.socket) { //先判断socket是否创建好
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                //通过socket 发送消息
                var sendId = document.getElementById("sendId").value;
                var myObj = {userId: sendId, msg: message};
                var messageJson = JSON.stringify(myObj);
                socket.send(messageJson)
            } else {
                alert("连接没有开启");
            }
        }
    </script>
</head>
<body>
<h1 th:text="${userId}"></h1>
<input type="hidden" th:value="${userId}" id="userId">
<input type="hidden" th:value="${sendId}" id="sendId">
<form onsubmit="return false">
    <textarea name="message" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="发送" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>
